package com.graduation.talk.controller;


import com.graduation.client.StudentClint;
import com.graduation.common.result.R;
import com.graduation.common.utils.JwtHelper;
import com.graduation.model.entity.BaseEntity;
import com.graduation.model.entity.DiscussionArea;
import com.graduation.model.entity.Student;
import com.graduation.model.vo.BlogVo;
import com.graduation.model.vo.ReportDiscussVo;
import com.graduation.model.vo.ReportVo;
import com.graduation.rabbit.config.MQConst;
import com.graduation.rabbit.service.RabbitService;
import com.graduation.talk.service.DiscussionAreaService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 * 这个是文章
 *
 * @author tianwenle
 * @since 2023-03-08
 */
@RestController
@RequestMapping("/user/talk/discussionArea")
public class DiscussionAreaController {

    @Autowired
    private DiscussionAreaService discussionAreaService;

    @Autowired
    private StudentClint studentClint;

    @Autowired
    private RabbitService rabbitService;

    @GetMapping("/getCurrentUserId")
    public R getCurrentUser(HttpServletRequest request) {
        // 获取token 解析数据到话题类
        String token = request.getHeader("X-Token");
        // 获取登录账号 查询用户的姓名
        String username = JwtHelper.getUserName(token);
        String power = JwtHelper.getPower(token);
        // 获取用户的id
        Long studentId = studentClint.getStudentIdByUsername(username);

        return R.ok().data("uid", studentId);
    }


    // 获取指定的主题 | 获取发布者的详细信息
    @GetMapping("/getDiscussById/{id}")
    public R getDiscussById(@PathVariable("id") Long id) {

        Map<String, Object> map = discussionAreaService.getDetailAboutDiscuss(id);

        return R.ok().data(map);
    }


    /**
     * 添加话题
     *
     * @param blogVo
     * @param request
     * @return
     */
    @PostMapping("/add")
    public R addDiscuss(@RequestBody BlogVo blogVo, HttpServletRequest request) {

        // 发布话题
        DiscussionArea discussionArea = new DiscussionArea();
        // 数据拷贝
        BeanUtils.copyProperties(blogVo, discussionArea);

        // 获取token 解析数据到话题类
        String token = request.getHeader("X-Token");
        // 获取登录账号 查询用户的姓名
        String username = JwtHelper.getUserName(token);
        String power = JwtHelper.getPower(token);
        // 获取用户的id
        Long studentId = studentClint.getStudentIdByUsername(username);
        // 这里只开放学生讨论区
        discussionArea.setUserId(studentId);

        // 保存数据
        discussionAreaService.save(discussionArea);

        return R.ok();
    }

    @DeleteMapping("/delete/{id}")
    public R deleteDiscuss(@PathVariable("id") Long id) {

        discussionAreaService.removeById(id);

        return R.ok();
    }

    @PutMapping("/update")
    public R updateDiscuss(@RequestBody DiscussionArea discussionArea) {
        discussionAreaService.updateById(discussionArea);
        return R.ok();
    }

    /**
     * 查询所有的讨论
     * 获取最新的讨论话题
     *
     * @return
     */
    @GetMapping("/getAllDiscuss")
    public R getAllDiscussNew() {
        // 数据展示不多 没必要采用分页
        List<DiscussionArea> list = discussionAreaService.list();
        // 按照时间排序
        list = list.stream().sorted(new Comparator<DiscussionArea>() {
            @Override
            public int compare(DiscussionArea discussionArea, DiscussionArea t1) {
                return t1.getUpdateTime().compareTo(discussionArea.getUpdateTime());
            }
        }).collect(Collectors.toList());
        // 这里的排序是正序
//        list.sort(Comparator.comparing(BaseEntity::getUpdateTime));
        // 这里获取到发布人的id 再根据id获取发布人的名字
        packageInfo(list);
        return R.ok().data("list", list);
    }

    private void packageInfo(List<DiscussionArea> list) {
        for (DiscussionArea discussionArea : list) {
            // 获取用户id
            Long userId = discussionArea.getUserId();
            // 查询用户名
            Student student = studentClint.getStudent(userId);
            discussionArea.setUsername(student.getUsername());
        }


    }


    // 按热度排名话题
    @GetMapping("/getAllDiscussByTopic")
    public R getAllDiscussByTopic() {

        List<DiscussionArea> list = discussionAreaService.lambdaQuery().orderByDesc(DiscussionArea::getAgree).list();

        packageInfo(list);

        return R.ok().data("list", list);
    }

    // 获取自己发表的话题
    @GetMapping("/getAllDiscussOfMine")
    public R getAllDiscussOfMine(HttpServletRequest request) {
        // 获取token
        String token = request.getHeader("X-Token");
        // 获取登录账号 查询用户的姓名
        String username = JwtHelper.getUserName(token);
        // 查询自己发布的话题
        Long studentId = studentClint.getStudentIdByUsername(username);
        List<DiscussionArea> list = discussionAreaService.lambdaQuery().eq(DiscussionArea::getUserId, studentId).list();
        packageInfo(list);
        return R.ok().data("list", list);
    }


    @PostMapping("/reportDiscuss")
    public R reportDiscuss(@RequestBody ReportVo reportVo) {
        // 获取文章的id
        Long id = reportVo.getId();
        // 获取用户举报的说明
        String content = reportVo.getContent();
        // http://localhost:9529/#/common/show/1642476565943746562
        ReportDiscussVo reportDiscussVo = new ReportDiscussVo();
        reportDiscussVo.setUrl("http://localhost:9529/#/common/show/" + id);
        reportDiscussVo.setContent(content);
        // 发送异步通知
        rabbitService.save(MQConst.EXCHANGE_DIRECT_EMAIL, MQConst.ROUTING_EMAIL, reportDiscussVo);
        return R.ok();
    }


}

